<!--
	时间：2020-12-10
	描述：对账明细汇总统计报表
-->

<!--<template>-->
<template>
  <div class="m-view-goodsAccountBill2 m-window">
    <!--查询条件-->
    <div class="m-condition" v-show="!isGoodsShow && !isAccountShow">
      <el-row :gutter="10">
        <el-form
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
          <el-col :span="7">
            <el-form-item :label="permission==4?'客户':'公司'" class="rightItem">
              <el-select
                value-key="id"
                ref="content"
                v-model="searchForm.companyCode"
                :placeholder="`请选择${permission==4?'客户':'公司'}`"
                @change="companyChange"
                filterable
                clearable
              >
                <el-option
                  v-for="item in comOptions"
                  :key="item.id"
                  :label="item.companyName"
                  :value="item.companyCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="入库日期" class="rightItem">
              <el-date-picker
                v-model="searchForm.postDateStart"
                type="date"
                placeholder="入库开始日期"
                value-format="yyyy-MM-dd"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-date-picker
              v-model="searchForm.postDateEnd"
              type="date"
              placeholder="入库结束日期"
              value-format="yyyy-MM-dd"
              ref="endPicker"
              @focus="endDateFocus"
              :picker-options="pickerEndOptions"
            ></el-date-picker>
          </el-col>
          <el-col :span="4">
            <el-form-item label="采购单号" class="rightItem">
              <el-input
                v-model="searchForm.purOrdNo"
                placeholder="请输入采购订单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label="入库单号" class="rightItem">
              <el-input
                v-model="searchForm.instockNo"
                placeholder="请输入入库单号"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-row :gutter="10">
        <el-form
          label-width="70px"
          :inline-message="true"
          label-position="left"
        >
          <el-col :span="7" v-if="permission==1">
            <el-form-item label="供应商" class="rightItem">
              <el-input
                placeholder="请选择供应商"
                v-model="selCusName"
                clearable
                @focus="showSupplierDialog"
                readonly
                @mouseenter.native="mouseEnter"
                @mouseleave.native="mounseLeave"
              >
                <el-button
                  slot="append"
                  icon="el-icon-search"
                  @click="showSupplierDialog"
                ></el-button>
                <span
                  slot="suffix"
                  @click="inputClearSon"
                  class="m-cleanInput"
                  v-show="inputClearBut"
                >
                  <i class="el-input_icon el-icon-circle-close el-input__clear"></i>
                </span>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="permission==4?7:5">
            <el-form-item label="物料描述" class="rightItem">
              <el-input
                v-model="searchForm.matName"
                placeholder="请输入物料描述"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="permission==4?5:4">
            <el-form-item label="实物对账单" class="rightItem">
              <el-input
                v-model="searchForm.gooAccNo"
                placeholder="请输入实物对账单"
                clearable
              ></el-input>
            </el-form-item>
          </el-col>
        </el-form>
        <el-col :span="2" class="m-floatRight">
          <el-button type="primary" @click="searchReport(1)">查询</el-button>
        </el-col>
      </el-row>
    </div>
    <!--采购订单跟踪列表-->
    <div
      class="m-agTable m-bottom m-top2"
      v-loading="loading"
      v-show="!isGoodsShow && !isAccountShow"
    >
      <agGridComponents
        ref="reportGridComponent"
        :getGridOptions="reportGridOptions"
        :getColumnDefs="reportColumnDefs"
        :getRowSelection="reportRowSelection"
        :isColFit="isColFit"
      ></agGridComponents>
    </div>
    <!-- 分页 -->
    <div class="m-page" v-show="!isGoodsShow && !isAccountShow">
      <el-pagination
        @size-change="reportHandleSizeChange"
        @current-change="reportHandleCurrentChange"
        :current-page="reportCurrentPage"
        :page-sizes="[30, 50, 100, 150, 200]"
        :page-size="reportPageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="reportTotal"
      ></el-pagination>
    </div>
    <!-- 调用实物对账单组件 -->
    <div class="m-window" v-if="isGoodsShow">
      <physicalApplyComponents
        @cancelComponents="cancelComponents"
        :pageLayOut="pageLayOut"
        :setClickValue="billDetails"
      ></physicalApplyComponents>
    </div>

    <!-- 调用会计对账单组件 -->
    <div class="m-window" v-if="isAccountShow">
      <accountApplyComponents
        @cancelComponents="cancelComponents"
        :pageLayOut="pageLayOut"
        :setClickValue="billDetails"
      ></accountApplyComponents>
    </div>
    <!-- 供应商弹窗 -->
    <el-dialog
      title="供应商信息"
      :visible.sync="srmSupplierDialogVisible"
      width="50%"
      :before-close="srmSupplierDialogClose"
      v-dialogDrag
      :close-on-click-modal="false"
      :close-on-press-escape="false"
    >
      <srmSupplierInfo
        ref="srmSupplierInfo"
        :layout="layout"
        @setSrmSupplierInfo="setSrmSupplierInfo"
      ></srmSupplierInfo>
    </el-dialog>
  </div>
</template>

<!--<script>-->
<script>
import _Api from '@/api';
import localeText from '@/i18n/agGridText';
import constant from '@/public/constant';
import agGridComponents from '@/components/agGridComponents.js';
import srmSupplierInfo from '@/components/srmSupplierInfo.vue';
import buttonLink from '@/components/buttonLink.js';
import Msg from '@/public/message';
import physicalApplyComponents from '@/views/accountManagement/physicalApplyComponents.vue';
import accountApplyComponents from '@/views/accountManagement/accountApplyComponents.vue';
/**
 * @group purchaseReport
 * 对账明细统计报表
*/
export default {
  data() {
    return {
        // vuese
        // 查询参数
        searchForm: {
        companyCode: '',
        gooAccNo: '',
        instockNo: '',
        matName: '',
        postDateEnd: '',
        postDateStart: '',
        purOrdNo: '',
        },
        //   vuese
        // 消息提示内容
        alertMessage: '',
        //   vuese
        // 公司列表
        comOptions: [],
        //   vuese
        // 供应商弹窗的可见性
        srmSupplierDialogVisible: false, 
        //   vuese
        // 供应商弹窗配置
        layout: {},
        //   vuese
        // 选择的供应商名称
        selCusName: '',
        //   vuese
        // 选择的供应商编码
        selCusCode: '',
        //   vuese
        // 是否显示清除按钮
        inputClearBut: false,
        //   vuese
        //   表格配置
        reportGridOptions: '',
        //   vuese
        // 表格列配置
        reportColumnDefs: [],
        //   vuese
        // 设置表格多选
        reportRowSelection: 'multiple',
        //   vuese
        // 分页相关配置
        reportCurrentPage: 1, //当前页码
        reportPageSize: 30, //页容量
        reportTotal: 0, //数据总量
        permission: '', //权限
        isColFit: true,
        //   vuese
        // 是否显示实物对战单详情
        isGoodsShow: false,
        //   vuese
        // 是否显示会计对账单详情
        isAccountShow: false,
        //   vuese
        // 对账单详情状态
        pageLayOut: 'view',
        loading: false,
        rowData: [],
        //   vuese
        // 对账单详情数据
        billDetails:null,
        //  vuese
        // 结束日期选项配置
        pickerEndOptions: this.endStartOptions(),
    };
  },
  created() {
    //   获取权限公司
    this.getAuthInfo();
  },
  beforeMount() {
    //   表格配置
    this.reportGridOptions = {
      context: {
        componentParent: this,
      },
      rowSelection: 'single',
      enableColResize: true,
      localeText: localeText,
      suppressRowClickSelection: true,
    };

    this.isColFit = true;
    // 行配置
    this.reportColumnDefs = [
      { headerName: '公司', field: 'companyName', width: 260 },
      { headerName: '供应商', field: 'supplierName', width: 260 },
      { headerName: '采购订单号', field: 'purOrdNo', width: 120 },
      { headerName: '行项目号', field: 'purOrdMxNo', width: 100 },
      { headerName: '物料编号', field: 'matCode', width: 120 },
      { headerName: '物料描述', field: 'matName', width: 260 },
      { headerName: '入库单号', field: 'instockNo', width: 100 },
      {
        headerName: '入库日期',
        field: 'postDate',
        width: 120,
        valueFormatter: (params) => {
          if (params.value) {
            return params.value.substr(0, 10);
          } else {
            return '';
          }
        },
      },
      {
        headerName: '实物对账单',
        field: 'gooAccNo',
        width: 150,
        cellRenderer: buttonLink,
      },
      {
        headerName: '实对状态',
        field: 'goodsState',
        width: 100,
        valueFormatter: (params) => {
          if (params.value == 1) {
            return '已保存';
          } else if (params.value == 2) {
            return '已提交';
          } else if (params.value == 3) {
            return '已确认';
          }
        },
      },
      {
        headerName: '会计对账单',
        field: 'accountNo',
        width: 160,
        cellRenderer: buttonLink,
      },
      {
        headerName: '会对状态',
        field: 'accountState',
        width: 100,
        valueFormatter: (params) => {
          if (params.value == 1) {
            return '已保存';
          } else if (params.value == 2) {
            return '已提交';
          } else if (params.value == 3) {
            return '已确认';
          } else if (params.value == 4) {
            return '已审核';
          }
        },
      },
      {
        headerName: '签署状态',
        field: 'signState',
        width: 100,
        valueFormatter: (params) => {
          if (params.value == 1) {
            return '未签署';
          } else if (params.value == 2) {
            return '签署中';
          } else if (params.value == 3) {
            return '签署完成';
          }
        },
      },
    ];
  },
  mounted() {
    this.$nextTick(() => {
      this.$refs.reportGridComponent.gridOptions.api.setRowData(this.rowData);
    });
  },
  components: {
    agGridComponents,
    srmSupplierInfo,
    physicalApplyComponents,
    accountApplyComponents,
  },
  methods: {
    /**
     * @vuese
     * 结束日期不可选择配置
    */
    endStartOptions() {
      let that = this;
      return {
        disabledDate(time) {
          const { postDateStart } = that.searchForm;
          let currentDate = new Date(time).getTime();
          if (postDateStart) {
            let startTime = new Date(`${postDateStart} 00:00:00`).getTime();
            if (currentDate < startTime) {
              return true;
            }  else {
              return false;
            }
          }
        },
      };
    },
    /**
     * @vuese
     * 结束日期控件聚焦回调
     */
    endDateFocus() {
      if (!this.searchForm.postDateStart) {
        Msg.showPopMsg("请先选择开始日期");
        this.$refs["endPicker"].blur();
      }
    },
    /**
     * @vuese
     * 选择公司名称回调
     * @arg 参数companyCode为公司编码
    */
    companyChange(companyCode) {
      if (this.permission == 1) {
        if (companyCode) {
          this.layout.companyCode = companyCode;
          this.layout.auth = true;
          // this.layout.filterByUser = true;
          if (this.selCusCode) this.selCusCode = '';
          if (this.selCusName) this.selCusName = '';
        } else {
          this.layout = {};
          this.selCusName = '';
          this.selCusCode = '';
        }
      }
      // this.currentPage = 1;
    },
    /**
     * @vuese
     * 打开选择供应商选择弹窗
    */
    showSupplierDialog() {
      if (!this.layout.companyCode) {
        this.$alert('提示：请选择公司！', {
          showClose: false,
          confirmButtonText: '确定',
          customClass: 'alertPrompt',
        });
        this.$refs.content.focus();
        return;
      } else {
        this.srmSupplierDialogVisible = true;
        this.$nextTick((_) => {
          this.$refs.srmSupplierInfo.search();
        });
      }
    },
    /**
     * @vuese
     * 关闭选择供应商弹窗回调
    */
    srmSupplierDialogClose(done) {
      this.$refs.srmSupplierInfo.keyWord = '';
      this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
        this.$refs.srmSupplierInfo.keyWord
      );
      done();
    },
    /**
     * @vuese
     * 输入框清除事件监听
    */
    inputClearSon() {
      this.selCusCode = '';
      this.selCusName = '';
      this.inputClearBut = false;
    },
    /**
     * @vuese
     * 回显选择的供应商信息
    */
    setSrmSupplierInfo(msg) {
      if (msg.length > 0) {
        this.$refs.srmSupplierInfo.keyWord = '';
        this.$refs.srmSupplierInfo.selSupplierOptions.api.setQuickFilter(
            this.$refs.srmSupplierInfo.keyWord
        );
        this.srmSupplierDialogVisible = false;
        this.selCusCode = msg[0].supplierCode;
        this.selCusName = msg[0].supplierName;
      }
    },
    /**
     * @vuese
     * 供应商输入框鼠标移入事件监听
    */
    mouseEnter() {
      if (this.selCusName != '') this.inputClearBut = true;
    },
    /**
     * @vuese
     * 供应商输入框鼠标移出事件监听
    */
    mounseLeave() {
      if (this.selCusName != '') this.inputClearBut = false;
    },
    /**
     * @vuese
     * 每页显示条数改变回调
     * @arg 参数size当前显示条数
    */
    reportHandleSizeChange(size) {
      this.reportPageSize = size;
      this.searchReport(1);
    },
    /**
     * @vuese
     * 页码改变回调
     * @arg 参数current当前页码
    */
    reportHandleCurrentChange(current) {
      this.reportCurrentPage = current;
      this.searchReport();
    },
    /**
     * @vuese
     * 查询报表数据
     * @arg 参数temp重置页码标识
    */
    searchReport(temp) {
        if(temp)this.reportCurrentPage = 1
      if (this.searchForm.companyCode) {
        if (!this.searchForm.postDateStart) {
          Msg.showPopMsg('请选择入库开始日期!');
          return;
        } else if (!this.searchForm.postDateEnd) {
          Msg.showPopMsg('请选择入库结束日期!');
          return;
        } else if (
          Date.parse(this.searchForm.postDateEnd) <
          Date.parse(this.searchForm.postDateStart)
        ) {
          Msg.showPopMsg('入库结束日期不能早于入库开始日期,请重新选择!');
          return;
        }
      } else {
        if(this.searchForm.postDateStart&&this.searchForm.postDateEnd){
          Msg.showPopMsg('请选择公司!');
          return;
        }
        if (
          !this.searchForm.purOrdNo &&
          !this.searchForm.instockNo &&
          !this.searchForm.gooAccNo && !this.searchForm.postDateStart&&!this.searchForm.postDateEnd
        ) {
          Msg.showPopMsg(
            '请先输入采购订单号/入库单号/实物对账单号/(公司+入库日期)进行查询！'
          );
          return;
        }
      }
      let params = {
        ...this.searchForm,
        gooAccNo: this.searchForm.gooAccNo.trim(),
        instockNo: this.searchForm.instockNo.trim(),
        matName: this.searchForm.matName.trim(),
        purOrdNo:this.searchForm.purOrdNo.trim(),
        postDateEnd: this.searchForm.postDateEnd
          ? `${this.searchForm.postDateEnd} 00:00:00`
          : '',
        postDateStart: this.searchForm.postDateStart
          ? `${this.searchForm.postDateStart} 00:00:00`
          : '',
        current: this.reportCurrentPage,
        pageSize: this.reportPageSize,
        supplierCode: this.selCusCode,
      };
      this.loading = true;
      this.$http
        .getAccountSumReport(params)
        .then(({ data }) => {
          this.loading = false;
          if (data.code == 1) {
            this.$refs.reportGridComponent.gridOptions.api.setRowData(
              data.rows
            );
            this.reportTotal = data.total
            this.rowData = data.rows;
          } else {
            Msg.showErrorMsg(data.info);
          }
        })
        .catch((err) => {
          this.loading = false;
          Msg.showErrorMsg(err.data.message);
        });
    },
    /**
     * @vuese
     * 获取当前账号权限公司
    */
    getAuthInfo() {
      //获取当前账号权限公司
      let obj = {};
      //帐号类型：4为供应商
      if (this.$global.user.userTypeId == 4) {
        obj.account = this.$global.user.userName;
        obj.userType = 2;
        this.alertMessage = '请选择客户！';
        this.selCusCode = constant.supplierData.supplierCode; //设置默认供应商编码
        this.postStatus = 1;
        this.permission = this.$global.user.userTypeId;
      }
      //帐号类型：1为内部员工
      else if (this.$global.user.userTypeId == 1) {
        obj.account = this.$global.user.oaNum;
        obj.userType = 1;
        this.alertMessage = '请先选择公司!';
        this.permission = this.$global.user.userTypeId;
      }
      this.comOptions = [];
      _Api
        .getAuthInfo(obj)
        .then((response) => {
          let data = response.data;
          if (data.code == 1) {
            //绑定公司选项
            if (
              Array.isArray(data.rows.myMstCompany) &&
              data.rows.myMstCompany.length > 0
            ) {
              this.comOptions = data.rows.myMstCompany;
              this.searchForm.companyCode = this.comOptions[0].companyCode;
              this.layout.companyCode = this.comOptions[0].companyCode;
              this.layout.auth = true;
              this.searchForm.postDateEnd = new Date().Format('yyyy-MM-dd')
              this.searchForm.postDateStart = new Date(Date.parse(new Date()) - 30*24*60*60*1000).Format('yyyy-MM-dd')
              this.searchReport(1)
            }
          } else {
            this.comOptions = [];
          }
        })
        .catch((err) => {
          this.$alert(err.data.message, {
            showClose: false,
            confirmButton: '确定1',
            customClass: 'alertFailure',
          });
          this.comOptions = [];
        });
    },
    /**
     * @vuese
     * 表格自定义渲染按钮点击事件回调
     * @arg 参数params为当前点击行对象
    */
    setClickValue(params) {
      if (params.value) {
        if (params.value.indexOf('SW') > -1) {
          this.loading = true;
          this.$http
            .getGoodsAccountBillById({ id: params.node.data.gooAccId })
            .then((response) => {
              this.loading = false;
              let data = response.data;
              if (data.code == '1') {
                if (data.rows) {
                  this.billDetails = data.rows;
                  this.isGoodsShow = true;
                  this.isAccountShow = false;
                }
              } else {
                Msg.showErrorMsg(data.info);
              }
            })
            .catch((err) => {
              this.loading = false;
              Msg.showErrorMsg(err.data.message);
            });
        } else if (params.value.indexOf('KJ') > -1) {
          this.loading = true;
          this.$http
            .getAccountBillById({ id: params.node.data.accountId })
            .then((response) => {
              this.loading = false;
              let data = response.data;
              if (data.code == '1') {
                if (data.rows) {
                  this.billDetails = data.rows;
                  this.isGoodsShow = false;
                  this.isAccountShow = true;
                }
              } else {
                Msg.showErrorMsg(data.info);
              }
            })
            .catch((err) => {
              this.loading = false;
              Msg.showErrorMsg(err.data.message);
            });
        }
      }
    },
    /**
     * @vuese
     * 关闭详情页回调
    */
    cancelComponents(msg) {
      if (msg) {
        this.isGoodsShow = false;
        this.isAccountShow = false;
        this.$nextTick(() => {
          this.$refs.reportGridComponent.gridOptions.api.setRowData(
            this.rowData
          );
        });
      }
    },
  },
  props: {
    removeTab: {
      type: Function,
    },
  },
};
</script>
